<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>标签列表</span>
			<el-button v-permission="'article:tag:create'" type="primary" plain icon="el-icon-circle-plus-outline"
				@click="insert_dialog_visible = true">
				添加标签
			</el-button>
		</div>
		<el-table :data="tableData">
			<el-table-column prop="tag_id" label="#"></el-table-column>
			<el-table-column prop="tag_name" label="标签名称"></el-table-column>
			<!-- 特殊时间格式的处理 -->
			<el-table-column label="创建时间">
				<template slot-scope="scope">
					<span>{{ localTimestamp(scope.row.create_date) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="更新时间">
				<template slot-scope="scope">
					<span>{{ localTimestamp(scope.row.update_date) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200">
				<!-- 复杂结构的固定写法：slot-scope="scope" ,scope.row要在slot-scope="scope"内，作用域插槽-->
				<template slot-scope="scope">
					<el-button type="primary" v-permission="'article:tag:edit'" @click="openEditDialog(scope.row)" plain
						icon="el-icon-edit">编辑
					</el-button>
					<el-button type="danger" plain icon="el-icon-delete" v-permission="'article:tag:remove'"
						@click="handleRemove(scope.row.tag_id, scope.$index)">删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 添加标签 -->
		<el-dialog title="添加标签" :visible.sync="insert_dialog_visible" @close="handleCloseDialog('insert_form')">
			<el-form :model="insert_form" ref="insert_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="标签名称:" prop="tag_name">
					<el-input type="text" v-model="insert_form.tag_name" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="insert_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleInsert">添加</el-button>
			</span>
		</el-dialog>

		<!-- 编辑标签 -->
		<el-dialog title="编辑标签" :visible.sync="edit_dialog_visible" @close="handleCloseDialog('edit_form')">
			<el-form :model="edit_form" ref="edit_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="标签名称:" prop="tag_name">
					<el-input type="text" v-model="edit_form.tag_name" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="edit_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleEdit">保存</el-button>
			</span>
		</el-dialog>
	</el-card>
</template>

<script>
import { Tag } from '@/api';
export default {
	// 组件的名称，便于搜索
	name: 'List',
	data() {
		return {
			insert_form: {
				tag_name: '',
				create_date: new Date().toLocaleString(),
				update_date: new Date().toLocaleString(),
			},
			edit_form: { tag_name: '' },
			tableData: [],
			insert_dialog_visible: false,
			edit_dialog_visible: false,
			rules: {
				tag_name: [{ required: true, message: "请填写标签名称！", trigger: 'blur' }]
			},
			// 缓存当前操作的row--指针地址
			current_tag: '',
		}
	},
	// 在created或mounted发送ajax请求(通过调用函数)
	created() {
		document.title = "标签列表页";
		this.loadList();
	},
	computed: {
		// 计算属性传参
		localTimestamp() {
			return (timestamp) => {
				return new Date(timestamp).toLocaleString()
			}
		},
	},
	methods: {
		// 一般将发送AJAX写到methods中
		// 加载列表
		async loadList() {
			let { status, msg, data } = await Tag.list({ pagesize: 10, pageindex: 1 });
			if (status) {
				this.tableData = data;
			} else {
				this.$message.error(msg);
			}
		},
		// 添加标签
		handleInsert() {
			// 1.表单验证
			this.$refs.insert_form.validate(async (valid) => {
				if (valid) {
					// 后台返回的data数据包含tag_id，由后台返回
					let { status, msg, data } = await Tag.create({ ...this.insert_form });
					if (status) {
						// 操作 DOM -- 拷贝(单层对象-浅拷贝；多层对象-深拷贝)
						this.tableData.push({ ...this.insert_form, ...data });
						// 关闭弹窗
						this.insert_dialog_visible = false;
						// 添加成功信息提示
						this.$message.success(msg);
					} else {
						// 添加失败信息提示
						this.$message.error(msg);
					}
				}
			});
		},
		// 打开编辑弹窗
		openEditDialog(tag) {
			// 缓存当前操作的tag，为了后续的操作DOM，存的是指针地址
			this.current_tag = tag;
			// 还原表单数据，浅拷贝一个，让点击保存后才能生效(双向数据绑定在修改的同时内容跟着变，不符合实际需求)
			this.edit_form = { ...tag };
			// 打开弹窗
			this.edit_dialog_visible = true;
		},
		// 编辑标签
		async handleEdit() {
			let { tag_id } = this.edit_form;
			// 验证表单(方法2)
			try {
				let valid = await this.$refs.edit_form.validate();
				if (valid) {
					// 发送AJAX
					let { status, msg } = await Tag.edit(tag_id, { ...this.edit_form });
					if (status) {
						// 操作DOM：让vue知道我们修改了数据，后续vue会自动虚拟DOM、对比等操作，从而实现数据的更新
						// 方法1
						// this.current_tag.tag_name = this.edit_form.tag_name;
						// 方法2
						Object.assign(this.current_tag, this.edit_form);
						// 关闭弹窗
						this.edit_dialog_visible = false;
						// 添加成功信息提示
						this.$message.success(msg);
					} else {
						// 添加失败信息提示
						this.$message.error(msg);
					}
				}
			} catch (error) {
				console.log(error);
			}
		},
		// 关闭弹窗，清除表单验证状态
		handleCloseDialog(formName) {
			// formName是变量，不能使用 ref.formName
			this.$refs[formName].resetFields();
		},
		// 删除标签
		handleRemove(tag_id, index) {
			// console.log(tag_id);
			this.$confirm('此操作将永久删除该标签, 是否继续?', '警告', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Tag.remove(tag_id);
					if (status) {
						// 操作 DOM
						this.tableData.splice(index, 1);
						// 信息提示
						this.$message.success(msg);
					} else {
						// 信息提示
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info('已取消删除！');
				});
		},
	},
}
</script>

<style lang="less" scoped>
.clearfix {
	display: flex;
	justify-content: space-between;
}
</style>
